package com.editoken.mp.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.editoken.mp.domain.dto.PageDTO;
import com.editoken.mp.domain.po.User;
import com.editoken.mp.domain.query.UserQuery;
import com.editoken.mp.domain.vo.UserVO;
import com.editoken.mp.enums.UserStatus;
import com.editoken.mp.mapper.UserMapper;
import com.editoken.mp.service.IUserService;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    @Transactional
    public void deductMoneyById(Long id, Integer money) {

       User user = getById(id);

       if (user == null || user.getStatus() == UserStatus.FREEZE) {
           throw  new RuntimeException("用户状态异常");
       }

       if (user.getBalance() < money) {
           throw  new RuntimeException("用户余额不足");
       }
        // baseMapper 形式
//       baseMapper.deductBalance(id, money);


        // lambda 样式
        int remainMoney = user.getBalance() - money;
        lambdaUpdate()
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁
                .set(User::getBalance, remainMoney)
                .set(remainMoney == 0, User::getStatus, 2) // 构建SQL语句
                .update() // 执行
        ;
    }

    @Override
    public List<User> queryUsers(UserQuery query) {
      return lambdaQuery()
                .like(query.getName() != null, User::getUsername, query.getName())
                .eq(query.getStatus() != null, User::getStatus, query.getStatus())
                .gt(query.getMinBalance() != null,User::getBalance, query.getMinBalance())
                .lt(query.getMaxBalance() != null,User::getBalance, query.getMaxBalance()).list();
    }

    @Override
    public PageDTO<User> queryUsersPage(UserQuery query) {

        String name = query.getName();
        Integer status = query.getStatus();

        // 分页条件
        Page<User> page = Page.of(query.getPageNo(), query.getPageSize());

        if (query.getSortBy() != null) {
            page.addOrder(new OrderItem(query.getSortBy(), query.getIsAsc()));
        }else {
            // 默认按照更新时间排序
            page.addOrder(OrderItem.desc("update_time"));
        }
        /// 查询
        page(page);



        List<User> records = page.getRecords();
        if (records == null || records.isEmpty()) {
            return new PageDTO<User>(page.getTotal(),page.getPages(), Collections.emptyList());
        }

        return new PageDTO<User>(page.getTotal(), page.getPages(), records);

    }

}
